<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactFollow\Action\Sidebar;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ContactFollow\Contract\ContactFollowContract;
use MoChat\Plugin\ContactTrack\Constants\Event;
use MoChat\Plugin\ContactTrack\Constants\EventName;
use MoChat\Plugin\ContactTrack\Contract\ContactTrackContract;

/**
 * 添加跟进.
 *
 * Class StoreProcess
 * @Controller
 */
class Store extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkContactContract
     */
    protected $workContact;

    /**
     * @Inject
     * @var ContactFollowContract
     */
    protected $contactEmployeeProcess;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * 互动轨迹表.
     * @Inject
     * @var ContactTrackContract
     */
    private $track;

    /**
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @RequestMapping(path="/sidebar/contactFollow/store", methods="POST")
     */
    public function handle(): array
    {
        // 接收参数
        $params['contactId'] = (int) $this->request->input('contactId');
        $params['content'] = $this->request->input('content');
        $params['followTemplateId'] = (int) $this->request->input('followTemplateId', 0);
        // 校验参数
        $this->validated($params);

        $contact = $this->workContact->getWorkContactById($params['contactId']);

        # # 数据操作
        Db::beginTransaction();
        try {
            $data = [
                'corp_id' => user()['corpId'],
                'employee_id' => user()['id'],
                'contact_id' => $params['contactId'],
                'contact_process_id' => $contact['followUpStatus'],
                'follow_template_id' => $params['followTemplateId'],
                'content' => $params['content'],
            ];
            # # 添加跟进
            $id = $this->contactEmployeeProcess->createContactFollow($data);
            # # 记录轨迹
            $this->recordTrack($params['contactId'], $params['content'], $params['followTemplateId'], $id);
            Db::commit();
            return [$id];
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '编辑用户跟进状态失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'contactId' => 'required|integer|min:1|bail',
            'content' => 'required',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'contactId.required' => '客户id必传',
            'content.required' => '跟进内容必传',
        ];
    }

    /**
     * 记录轨迹.
     * @param $contactId
     * @param $content
     * @param $followTemplateId
     * @param $id
     */
    private function recordTrack($contactId, $content, $followTemplateId, $id)
    {
        $jsonContact = [
            'title' => $followTemplateId > 0 ? EventName::FOLLOW_TEMPLATE : EventName::FOLLOW,
            'content' => $content,
            'target_id' => $id,
        ];
        $data = [
            'employee_id' => user()['id'],
            'contact_id' => $contactId,
            'content' => Json::encode($jsonContact),
            'corp_id' => user()['corpId'],
            'target_id' => $id,
            'event' => $followTemplateId > 0 ? Event::FOLLOW_TEMPLATE : Event::FOLLOW,
        ];

        $res = $this->track->createContactTrack($data);
        if (! is_int($res)) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '记录轨迹失败');
        }
    }
}
